<template>
  <div id="map-wrapper">
    <div id="mapsearch-bar">
      <select v-model="travelMode" class="map-search-select">
        <option value="driving">驾车</option>
        <option value="walking">步行</option>
        <option value="transit">公交</option>
      </select>

      <input
        id="startInput"
        v-model="mapStartPoint"
        placeholder="起点"
        class="map-search-input"
        ref="startInput"
      />
      <input
        id="endInput"
        v-model="mapEndPoint"
        placeholder="终点"
        class="map-search-input"
        ref="endInput"
      />

      <button @click="mapSearchRoute" class="map-search-button">搜索</button>
    </div>

    <div id="container"></div>
    <div id="panel"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';

let map = null;
let geolocation = null;
let hawkEye = null;
let controlBar = null;
let driving = null;
let walking = null;
let transit = null;

const travelMode = ref('driving');
const mapStartPoint = ref('');
const mapEndPoint = ref('');
const mapStartCity = ref('');
const mapEndCity = ref('');
const autocompleteStart = ref(null);
const autocompleteEnd = ref(null);

onMounted(async () => {
  await nextTick(); // 确保 DOM 完全挂载

  window._AMapSecurityConfig = {
    securityJsCode: 'a37b057e319b17c0f41efd30ac8e7f01',
  };

  AMapLoader.load({
    key: 'aceb229cbcf9827134f48bc022aa99da', // 替换为你的高德 API Key
    version: '2.0',
    plugins: ['AMap.Driving', 'AMap.Walking', 'AMap.Transfer', 'AMap.AutoComplete', 'AMap.Geolocation', 'AMap.HawkEye', 'AMap.ControlBar'],
  })
    .then((AMap) => {
      // 初始化地图
      map = new AMap.Map('container', {
        pitch: 50, // 地图俯仰角度
        viewMode: '3D',
        rotateEnable: true,
        pitchEnable: true,
        resizeEnable: true,
        center: [87.618, 43.824599],
        zoom: 13,
      });

      // 添加定位控件
      geolocation = new AMap.Geolocation({
        position: 'LB', // 左下角
        offset: [1650, 240], // 偏移量
        borderColor: '#ccc', // 按钮边框颜色
        borderRadius: '5px', // 按钮圆角
        buttonSize: '30px', // 按钮大小
        convert: true, // 转换为高德坐标
        enableHighAccuracy: true, // 高精度定位
        timeout: 5000, // 超时时间 5 秒
        showMarker: true, // 显示定位点
        showCircle: true, // 显示定位精度圆
        panToLocation: true, // 自动移动到定位点
        zoomToAccuracy: true, // 自动调整地图级别到精度范围
      });
      map.addControl(geolocation);

      // 添加鹰眼控件
      hawkEye = new AMap.HawkEye({
        autoMove: true,
        showRectangle: true,
        showButton: true,
        opened: true,
        mapStyle: 'amap://styles/white',
        width: '200px',
        height: '200px',
        position: 'RB', // 右下角
        offset: [10, 10],
        borderStyle: 'solid',
        borderColor: '#ccc',
        borderWidth: '2px',
        borderRadius: '5px',
        buttonSize: '14px',
      });
      map.addControl(hawkEye);

      // 添加罗盘控件
      controlBar = new AMap.ControlBar({
        position: 'RT', // 右上角
        offset: [10, 10], // 偏移量
        showControlButton: true, // 显示旋转和倾斜按钮
      });
      map.addControl(controlBar);

      // 添加行驶、步行、公交搜索控件
      driving = new AMap.Driving({
        map: map,
        panel: 'panel',
      });

      walking = new AMap.Walking({
        map: map,
        panel: 'panel',
      });

      transit = new AMap.Transfer({
        map: map,
        city: '北京市',
        panel: 'panel',
        policy: AMap.TransferPolicy.LEAST_TIME,
      });

      // 补全控件
      autocompleteStart.value = new AMap.AutoComplete({
        input: document.getElementById('startInput'),
        city: mapStartCity.value || '北京',
      });

      autocompleteEnd.value = new AMap.AutoComplete({
        input: document.getElementById('endInput'),
        city: mapEndCity.value || '北京',
      });

      //事件监听
      autocompleteStart.value.on('select', (e) => {
        mapStartPoint.value = e.poi.name;
        console.log('选择起点:', e.poi);
      });

      autocompleteEnd.value.on('select', (e) => {
        mapEndPoint.value = e.poi.name;
        console.log('选择终点:', e.poi);
      });
    })
    .catch((e) => {
      console.error('AMap API 加载失败:', e);
    });
});

onUnmounted(() => {
  // 销毁地图
  if (map) {
    map.destroy();
  }
});

const mapSearchRoute = () => {
  if (!mapStartPoint.value || !mapEndPoint.value) {
    console.log('请输入起点和终点');
    return;
  }

  if (travelMode.value === 'driving') {
    driving.search(
      [
        { keyword: mapStartPoint.value, city: mapStartCity.value },
        { keyword: mapEndPoint.value, city: mapEndCity.value },
      ],
      function (status, result) {
        if (status === 'complete') {
          console.log('绘制驾车路线完成');
        } else {
          console.error('获取驾车数据失败：' + result);
        }
      }
    );
  } else if (travelMode.value === 'walking') {
    walking.search(
      [
        { keyword: mapStartPoint.value, city: mapStartCity.value },
        { keyword: mapEndPoint.value, city: mapEndCity.value },
      ],
      function (status, result) {
        if (status === 'complete') {
          console.log('绘制步行路线完成');
        } else {
          console.error('获取步行数据失败：' + result);
        }
      }
    );
  } else if (travelMode.value === 'transit') {
    transit.search(
      [
        { keyword: mapStartPoint.value, city: mapStartCity.value },
        { keyword: mapEndPoint.value, city: mapEndCity.value },
      ],
      function (status, result) {
        if (status === 'complete') {
          console.log('绘制公交路线完成');
        } else {
          console.error('获取公交数据失败：' + result);
        }
      }
    );
  }
};
</script>

<script>
export default {
  name: 'mapcontainer',
};
</script>

<style scoped>
#map-wrapper {
  position: relative;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  align-items: center;
}

#container {
  flex: 1;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

/* 覆盖定位按钮背景 */
.amap-geolocation button {
  background-color: red !important; /* 设置定位按钮背景为红色 */
  border: 1px solid red !important; /* 设置定位按钮边框为红色 */
}

/* 如果按钮内部有图标 */
.amap-geolocation button .amap-icon {
  color: white !important; /* 设置图标颜色为白色，保证对比度 */
}


#panel {
  position: fixed;
  background-color: white;
  max-height: 500px;
  overflow-y: scroll;
  top: 165px;
  left: 10px;
  width: 280px;
  opacity: 0.7;
}

#mapsearch-bar {
  display: flex;
  gap: 10px;
  margin-top: 10px;
  margin-bottom: 20px;
}

.map-search-input {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
  width: 250px;
  margin-right: 20px;
}

.map-search-button {
  padding: 10px 20px;
  background-color: #7fabbe;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.map-search-button:hover {
  background-color: #1e5631;
}

.map-search-select {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  width: 150px;
  margin-left: 10px;
  margin-right: 25px;
}
</style>
